"""
:copyright:
Copyright (C) 2007 Association of Universities for Research in Astronomy (AURA)

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above
      copyright notice, this list of conditions and the following
      disclaimer in the documentation and/or other materials provided
      with the distribution.

    3. The name of AURA and its representatives may not be used to
      endorse or promote products derived from this software without
      specific prior written permission.

THIS SOFTWARE IS PROVIDED BY AURA ``AS IS'' AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL AURA BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.


:Author: Christopher Hanley 

:Purpose: 
This application is used to create png files registered
to a valid WCS that would be appropriate for inporting
into GoogleSky.

Possible Input -
1) A single FITS image with valid WCS
2) Three FITs images representing 3 color bands.

:Outout:
A png file registered to a valid WCS

"""

# external dependencies
import pyfits
import numpy
import Image # Python Image Library
import os

# dependencies
import fitsimage
import wcslib
import wcs2kml

    
        
def fits2png(image,scaleOptions):
    """
    :Purpose: Given a single input FITS image create a color png registered with the FITS image.
    """
    hdr,data = readScienceData(image)
    image = fitsimage.FitsImage(hdr,
                                data,
                                contrast=scaleOptions['contrast'],
                                contrast_opts=scaleOptions,
                                scale=scaleOptions['scale'],
                                scale_opts=scaleOptions
                            )
    
    return image
    
    
def multifits2png(img1,img2,img3):
    """ 
    :Purpose: Given three input FITS images create a color png registered with the FITS image. 
    Each image can accept a weigth value between 0 and 100 representing the percentage
    each image is to contribute to the final image.  By default, all images will contribute
    100 percent to the final product.
    """
      
    pass

def readScienceData(fitsfile):
    """
    :Purpose: Given a FITS file read the science header,data and return
    
    """
    
    hdulist = pyfits.open(fitsfile)
    if hdulist[0].data is not None:
        return hdulist[0].header,hdulist[0].data
    else:
        return hdulist[1].header,hdulist["sci",1].data

def makeKMZ(image,referenceFITS,kmzoutputname):

    # Read Input
    fitsfile = referenceFITS
    
    # Set some default parameters
    max_side_length = 3000
    input_image_origin_is_lower_left = True
    imagefile = referenceFITS
    
    # Read the WCS.
#    fits = pyfits.open(fitsfile)
#    try:
#      header = fits[0].header
    header,data = readScienceData(fitsfile)
    wcs = wcslib.WcsProjection(header)
#    finally:
#      fits.close()
    
    # Set the various warping options and warp the input image.
    projection = wcs2kml.SkyProjection(image, wcs)
    projection.backgroundColor = (0, 0, 0, 0)
    projection.maxSideLength = max_side_length
    if input_image_origin_is_lower_left:
      projection.inputImageOrigin = wcs2kml.ImageOrigin.LOWER_LEFT
    else:
      projection.inputImageOrigin = ImageOrigin.UPPER_LEFT
    
    projected_image = projection.warpImage()
    
    # Write warped image to file.
    name, ext = os.path.splitext(imagefile)
    projected_imagefile = "%s_warped.png" % name
    
    projected_image.save(projected_imagefile)
    
    # Write bounding box to KML file.
    bounding_box = projection.boundingBox
    f = open("doc.kml", "w")
    try:
      f.write(bounding_box.toKml(projected_imagefile))
    finally:
      f.close()
    
    # Write KML and warped image to KMZ.
#    outfile = "%s.kmz" % name
    outfile = kmzoutputname


    wcs2kml.write_kmz(outfile, projected_imagefile, "doc.kml")
    
    # Clean up temporary files.
    os.remove("doc.kml")
    os.remove(projected_imagefile)
